package com.wqh.article.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.wqh.article.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author wanqh
 * @date 2018/01/14 16:42
 * @description:
 */
public class GetUserCommand  extends HystrixCommand<User> {
    private static final Logger logger = LoggerFactory.getLogger(GetUserCommand.class);


    private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("CommandKey");

    private RestTemplate restTemplate;
    private Long id;

    public GetUserCommand(RestTemplate restTemplate, Long id) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userGroup")));
        this.restTemplate = restTemplate;
        this.id = id;
    }
    @Override
    protected User run() throws Exception {
        logger.info(">>>>>>>>>>>>>查询操作>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return restTemplate.getForObject("http://USER-SERVICE/user/{1}", User.class, id);
    }
    @Override
    protected String getCacheKey() {
        //根据id保存缓存
        return String.valueOf(id);
    }
    /**
     * 根据id清理缓存
     * @param id
     */
    public static void flushCache(Long id){
        logger.info(" >>>>>>>>>>>>>GETTER_KEY:{}>>>>>>>>>>>>>>>>",GETTER_KEY);
        HystrixRequestCache.getInstance(GETTER_KEY,
                HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
    }
}
